package com.aweqy.librarymanager.controller;

import com.aweqy.librarymanager.entity.FineRecord;
import com.aweqy.librarymanager.service.FineRecordService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/api/fine")
public class FineRecordController {
    @Autowired
    private FineRecordService fineRecordService;

    // 罚款记录查询
    @GetMapping("/list")
    public Page<FineRecord> list(@RequestParam(defaultValue = "1") int page,
                                 @RequestParam(defaultValue = "10") int size,
                                 @RequestParam(required = false) Integer payStatus) {
        QueryWrapper<FineRecord> wrapper = new QueryWrapper<>();
        if (payStatus != null) {
            wrapper.eq("pay_status", payStatus);
        }
        return fineRecordService.page(new Page<>(page, size), wrapper);
    }

    // 支付罚款
    @PostMapping("/pay")
    public boolean pay(@RequestBody Map<String, Object> params) {
        Integer fineId = (Integer) params.get("fineId");
        FineRecord fine = fineRecordService.getById(fineId);
        if (fine != null && fine.getPayStatus() == 0) {
            fine.setPayStatus(1);
            fine.setPayTime(new Date());
            fineRecordService.updateById(fine);
            return true;
        }
        return false;
    }

    // 删除罚款记录
    @PostMapping("/delete")
    public ResponseEntity<?> delete(@RequestBody Map<String, Object> params) {
        Integer fineId = (Integer) params.get("fineId");
        if (fineId == null) {
            return ResponseEntity.badRequest().body("参数错误，缺少fineId");
        }
        boolean ok = fineRecordService.removeById(fineId);
        if (!ok) {
            return ResponseEntity.status(500).body("删除失败");
        }
        return ResponseEntity.ok(true);
    }

    // 新增罚款记录
    @PostMapping("/add")
    public ResponseEntity<?> add(@RequestBody FineRecord fineRecord) {
        if (fineRecord.getRecordId() == null || fineRecord.getOverdueDays() == null || fineRecord.getFineAmount() == null) {
            return ResponseEntity.badRequest().body("借阅记录ID、逾期天数、罚款金额不能为空");
        }
        if (fineRecordService.lambdaQuery().eq(FineRecord::getRecordId, fineRecord.getRecordId()).one() != null) {
            return ResponseEntity.badRequest().body("该借阅记录已存在罚款，请勿重复添加");
        }
        boolean ok = fineRecordService.save(fineRecord);
        if (!ok) {
            return ResponseEntity.status(500).body("保存失败，请联系管理员");
        }
        return ResponseEntity.ok(true);
    }
} 